package com.zyw.zhuangdian.service.impl;

import com.zyw.zhuangdian.constant.ServiceConstant;
import com.zyw.zhuangdian.dao.CarouselDao;
import com.zyw.zhuangdian.pojo.Resp;
import com.zyw.zhuangdian.pojo.dto.PageDto;
import com.zyw.zhuangdian.pojo.in.CarouselDtoIn;
import com.zyw.zhuangdian.pojo.out.CarouselDtoOut;
import com.zyw.zhuangdian.service.CarouselService;
import com.zyw.zhuangdian.util.BeanConvertUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class CarouselServiceImpl implements CarouselService {
    private final CarouselDao CarouselDao;

    @Override
    public Resp<Void> addCarousel(CarouselDtoIn in) {
        Resp<Void> resp = new Resp<>();

        CarouselDao.addCarousel(BeanConvertUtil.beanCovertMap(in));
        return resp;
    }

    @Override
    public Resp<Void> updateCarousel(CarouselDtoIn in) {
        Resp<Void> resp = new Resp<>();

        CarouselDao.updateCarousel(BeanConvertUtil.beanCovertMap(in));
        return resp;
    }

    @Override
    public Resp<Void> deleteCarousel(CarouselDtoIn in) {
        Resp<Void> resp = new Resp<>();
        in.setStatus(ServiceConstant.STATUS_INVALID);
        CarouselDao.updateCarousel(BeanConvertUtil.beanCovertMap(in));
        return resp;
    }

    @Override
    public Resp<List<CarouselDtoOut>> listCarousels(CarouselDtoIn in) {
        Resp<List<CarouselDtoOut>> resp = new Resp<>();
        if (in.getPage() != PageDto.DEFAULT_PAGE){
            if (in.getRow() == PageDto.DEFAULT_PAGE){
                in.setPage(PageDto.DEFAULT_PAGE);
            }else{
                in.setPage((in.getPage() - 1) * in.getRow());
            }
        }
        int count = CarouselDao.listCarouselsCount(BeanConvertUtil.beanCovertMap(in));
        if (count > 0){
            List<Map> articles = CarouselDao.listCarousel(BeanConvertUtil.beanCovertMap(in));
            List<CarouselDtoOut> dtoOuts = BeanConvertUtil.covertBeanList(articles,CarouselDtoOut.class);
            resp.setData(dtoOuts);
        }

        resp.setTotal(count);
        if (in.getPage() != PageDto.DEFAULT_PAGE) {
            resp.setRecords((int) Math.ceil((double) count / (double) in.getRow()));
            resp.setPage(in.getPage());
            resp.setRow(in.getRow());
        }
        return resp;
    }
}